# coding:utf-8
from alipay import AliPay
import time
import os
import sys
import json
from app import db
from app.home import home
from flask import request, jsonify, session, g, current_app
from app.models import Article, ArticleComment, ArticleSort, ReplyComment
from response_code import RET
from error_msg import LoggerError
from sqlalchemy.sql.expression import func

# --------------------------文章前端接口----------------------------------------
# 展示文章列表  标题  时间   类型    简介


@home.route("/arcs", methods=["GET", "POST"])
# 显示文章列表
def get_arc():
    # post获取文章加载更多数据
    if request.method == "POST":
        req_data = request.get_json()
        page = req_data.get("page")
        per_page = req_data.get("per_page")
        page = int(page)
        per_page = int(per_page)
        try:
            arcs = db.session.query(Article.id, Article.title, Article.content, ArticleSort.sort, Article.article_sort_id, Article.addtime).filter(Article.article_sort_id == ArticleSort.id, Article.is_del == 0).paginate(
                page, per_page, error_out=False)
            arc_data = {
                "current_page": arcs.page,
                "pages": arcs.pages,  # 总页数
                "arc_nums": arcs.total,  # 数据的总条数
                "arc_list": [{
                    "id": arc.id,
                    "title": arc.title,
                    "sort": arc.sort,
                    "sort_id": arc.article_sort_id,
                    "content": arc.content,
                    "addtime": str(arc.addtime)

                } for arc in arcs.items]
            }
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
        return jsonify(code=RET.OK, msg="获取文章列表成功", data=arc_data)
    else:
        try:
            arcs = db.session.query(Article.id, Article.title, Article.sort, Article.addtime).filter(
                Article.article_sort_id == ArticleSort.id, Article.is_del == 0).all()
            arc_data = [{
                "id": arc.id,
                "title": arc.title,
                "sort": arc.sort,
                "addtime": arc.addtime
            } for arc in arcs]
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    return jsonify(code=RET.OK, msg="获取文章列表成功", data=arc_data)


# 获取随机文章列表
@home.route("/random_arcs", methods=["GET"])
def get_random_arc():
    try:
        arcs = db.session.query(Article.id, Article.title).filter(
            Article.article_sort_id == ArticleSort.id, Article.is_del == 0).order_by(func.random()).limit(5).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    arc_data = [{
        "id": arc.id,
        "title": arc.title.strip()
    } for arc in arcs]
    return jsonify(code=RET.OK, msg="获取文章列表成功", data=arc_data)


# 获取查询文章数据
@home.route("/search_arcs", methods=["GET"])
def get_search_arc():
    title = request.args.get("search_wd")
    # 如果是查询字符串为空，返回10篇最新文章
    if not title:
        try:
            arcs_by_title = db.session.query(Article.id, Article.title).filter(
                Article.title.like('%{title}%'.format(title=title)),
                Article.article_sort_id == ArticleSort.id,
                Article.is_del == 0).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
        arc_data = [{
            "id": arc.id,
            "title": arc.title
        } for arc in arcs_by_title]
        return jsonify(code=RET.OK, msg="获取文章列表成功", data=arc_data)
    # 查询字符串不为空，根据文章标题字段进行查询
    try:
        arcs_by_title = db.session.query(Article.id, Article.title).filter(Article.title.like('%{title}%'.format(title=title)),
                                                                           Article.article_sort_id == ArticleSort.id,
                                                                           Article.is_del == 0).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    arc_data = [{
        "id": arc.id,
        "title": arc.title
    } for arc in arcs_by_title]
    # 如果根据文章标题查询数据为空则再根据文章类型进行查询
    if not arcs_by_title:
        try:
            arcs_by_sort = db.session.query(Article.id, Article.title).filter(ArticleSort.sort.like('%{title}%'.format(title=title)),
                                                                              Article.article_sort_id == ArticleSort.id,
                                                                              Article.is_del == 0).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
        arc_data = [{
            "id": arc.id,
            "title": arc.title
        } for arc in arcs_by_sort]
        # 根据查询字符串查询文章标题和文章类型字段都为空，返回错误
        if not arcs_by_sort:
            current_app.logger.error(LoggerError.NODATA)
            return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    # 查询到数据返回
    return jsonify(code=RET.OK, msg="获取文章列表成功", data=arc_data)


# 文章详情页   标题  时间  分类   富文本内容
@home.route("/arc_info", methods=["GET"])
def arc_info():
    arc_id = request.args['aid']
    if not arc_id:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="缺少查询的文章id")
    try:
        arc = db.session.query(Article.id, Article.title, ArticleSort.sort, Article.content, Article.addtime).filter(
            Article.id == arc_id, Article.article_sort_id == ArticleSort.id, Article.is_del == 0).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败", data="")
    arc_data = {
        "id": arc.id,
        "title": arc.title,
        "sort": arc.sort,
        "content": arc.content,
        "addtime": str(arc.addtime)
    }
    return jsonify(code=RET.OK, msg="获取文章详情页面成功", data=arc_data)


# 获取文章标签
@home.route("/arc_sort", methods=["GET"])
def arc_sort():
    try:
        arcs = db.session.query(ArticleSort.id, ArticleSort.sort).filter(
            ArticleSort.is_del == 0).all()
        tags = [{
            "id": arc.id,
            "name": arc.sort,
        }
            for arc in arcs]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败", data="")
    return jsonify(code=RET.OK, msg="获取文章标签数据成功", tags=tags)


# 获取文章时间轴标签
@home.route("/arc_sort_time", methods=["GET"])
def arc_sort_time():
    try:
        arcs = db.session.query(Article.id, Article.title, Article.addtime).filter(
            Article.is_del == 0).all()
        arc_data = [{
            "id": arc.id,
            "title": arc.title,
            "addtime": str(arc.addtime)}
            for arc in arcs]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败", data="")
    return jsonify(code=RET.OK, msg="获取文章时间轴数据成功", data=arc_data)


# 获取文章分类数据
@home.route("/arc_sort_list", methods=["GET"])
def get_arc_sort_list():
    sort_id = request.args.get("sort_id")
    # print(sort_id)
    if not sort_id:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="参数错误", data="")
    try:
        arcs = db.session.query(Article.id, Article.title, ArticleSort.sort, Article.addtime, Article.article_sort_id).filter(
            Article.article_sort_id == sort_id, Article.article_sort_id == ArticleSort.id).all()
        arc_data = [{
            "id": arc.id,
            "title": arc.title,
            "sort": arc.sort,
            "addtime": str(arc.addtime),
            "sort_id": arc.article_sort_id}
            for arc in arcs]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败", data="")
    return jsonify(code=RET.OK, msg="获取分类文章数据成功", data=arc_data)


# 文章评论接口
@home.route("/arc_comment", methods=["GET", "POST"])
def arc_comment():
    if request.method == "POST":
        req_data = request.get_json()
        arc_id = req_data.get("arc_id")
        nickname = req_data.get("nickname")
        email = req_data.get("email")
        comment = req_data.get("comment")
        img_url = req_data.get("img_url")
        if not all([nickname, comment]):
            current_app.logger.error(LoggerError.PARAMERROR)
            return jsonify(code=RET.PARAMERR, msg="参数错误", data="")
        comments = ArticleComment(
            article_id=arc_id,
            nick_name=nickname,
            comment=comment,
            email=email,
            face_img=img_url
        )
        try:
            db.session.add(comments)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="添加评论失败", data="")
        return jsonify(code=RET.OK, msg="添加评论成功")
    else:
        arc_id = request.args.get("arc_id")
        if not arc_id:
            current_app.logger.error(LoggerError.PARAMERROR)
            return jsonify(code=RET.PARAMERR, msg="参数错误", data="")
        try:
            arc_comments = db.session.query(ArticleComment.id, ArticleComment.nick_name, ArticleComment.comment, ArticleComment.addtime,
                                            ArticleComment.face_img).filter(ArticleComment.article_id == arc_id, ArticleComment.is_del == 0).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库查询失败", data="")
        if not arc_comments:
            current_app.logger.error(LoggerError.NODATA)
            return jsonify(code=RET.NODATA, msg="没有查询到评论数据", data="")
        arc_comment_data = []
        for arc_comment in arc_comments:
            try:
                reply_comments = db.session.query(ReplyComment.id, ReplyComment.reply_comment, ReplyComment.addtime).filter(
                    ReplyComment.comment_id == arc_comment.id, ReplyComment.is_del == 0).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(code=RET.DBERR, msg="数据库查询错误", data="")
            reply_data = [
                {
                    "id": reply_comment.id,
                    "reply_comment": reply_comment.reply_comment,
                }
                for reply_comment in reply_comments
            ]
            datas = {
                "id": arc_comment.id,
                "nick_name": arc_comment.nick_name,
                "comment": arc_comment.comment,
                "addtime": str(arc_comment.addtime),
                "face_img": arc_comment.face_img,
                "reply_data": reply_data
            }
            arc_comment_data.append(datas)
        return jsonify(code=RET.OK, msg="获取文章评论成功", data=arc_comment_data)
